// Copyright (c) 2009 Mike Haight, Andy Kipp
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

#include "Timer.h"

using namespace HandBanana::Utilities;


Timer::Timer(float argTimePerTick) : mTimePerTick(argTimePerTick), mAccumulatedTime(0), mFrequency(0), mStartTime(0)
{
    //
    // MSDN:
    // The QueryPerformanceFrequency function retrieves the frequency of the
    // high-resolution performance counter, if one exists. The frequency cannot
    // change while the system is running.
    //

    LARGE_INTEGER li = {0};

    // TODO: We should have a fallback if the performance counter is not supported
    if (FALSE == ::QueryPerformanceFrequency(&li))
    {
        throw std::exception("Performance timer is not supported.");
    }

    mFrequency = (float)li.QuadPart;
}


void Timer::BeginTiming(void)
{
    // Query the performance counter for the start time
    LARGE_INTEGER startTime = {0};
    ::QueryPerformanceCounter(&startTime);
    mStartTime = startTime.QuadPart;
}


void Timer::EndTiming(void)
{
    // Query the performance counter for the end time and save the total accumulated time
    LARGE_INTEGER endTime = {0};
    ::QueryPerformanceCounter(&endTime);
    mAccumulatedTime += (float)(endTime.QuadPart - mStartTime) / mFrequency;
}


void Timer::Reset(void)
{
    mAccumulatedTime = 0;
}


bool Timer::Tick(void) const
{
    return (mAccumulatedTime >= mTimePerTick);
}